package com.portal.cwegportal.service;

import com.appcenter.jz.app.CurrentUser;
import com.appcenter.jz.page.PagedResult;
import com.appcenter.jz.unit.ObjectUnit;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.portal.cwegportal.customenum.FileBusinessType;
import com.portal.cwegportal.customenum.FileClass;
import com.portal.cwegportal.input.browserecord.CreateBrowseRecordInput;
import com.portal.cwegportal.input.browserecord.GetBrowseCountInput;
import com.portal.cwegportal.input.newscollege.GetNewsCollegeInput;
import com.portal.cwegportal.mapper.ColumnPlateMapper;
import com.portal.cwegportal.mapper.NewsCollegeMapper;
import com.portal.cwegportal.mapper.ReleaseScopeMapper;
import com.portal.cwegportal.model.*;
import com.portal.cwegportal.model.Tool.PrivilegeTool;
import com.portal.cwegportal.output.newscollege.*;
import com.portal.cwegportal.input.newscollege.*;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import static org.apache.http.util.TextUtils.isBlank;
/**
 *  创建人:王增立
 *  备注: 新闻管理服务
 *  时间: 2019/4/26 15:13
 *  参数: 
 */
@Service
public class NewsCollegeService {

    @Autowired
    NewsCollegeMapper newsCollegeMapper;
    @Autowired
    ColumnPlateMapper columnPlateMapper;
    @Autowired
    ReleaseScopeMapper releaseScopeMapper;
    @Autowired
    FileService fileService;
    @Autowired
    BrowseRecordService browseRecordService;
    @Autowired
    PrivilegeService privilegeService;

/**
 *  创建人:王增立
 *  备注: 创建新闻
 *  时间: 2019/4/26 15:13
 *  参数: 
 */
    @Transactional
    public CreateNewsCollegeOutput createNewsCollege(CreateNewsCollegeInput input) throws Exception {
        CreateNewsCollegeOutput output = new CreateNewsCollegeOutput();
        NewsCollege NewsCollege = new NewsCollege();
        ObjectUnit.Copy(input.getItem(), NewsCollege);

        NewsCollege.setGmtCreate(new Date());
        NewsCollege.setGmtModified(new Date());
        //NewsCollege.setReleaseTime(new Date());
        NewsCollege.setDeleted(false);
        NewsCollege.setCreatorCode(CurrentUser.getUserCode());
        NewsCollege.setCreatorId(CurrentUser.getUserId());
        NewsCollege.setCreatorName(CurrentUser.getUserName());
        if(input.getItem().getId()!=null) {
            newsCollegeMapper.deleteByPrimaryKey(input.getItem().getId());
            releaseScopeMapper.deleteByKeyId(input.getItem().getId().toString(),NewsCollege.getPublishType());
            NewsCollege.setId(null);
        }
        //newsCollegeMapper.insertNewsCollegeAndGetId(NewsCollege);
        newsCollegeMapper.insertSelective(NewsCollege);
        fileService.saveFiles(input.getItem().getFiles(), NewsCollege.getId().toString(), FileBusinessType.NewsCollege.toString(), FileClass.File.toString());
        fileService.saveFiles(input.getItem().getImgFiles(), NewsCollege.getId().toString(), FileBusinessType.NewsCollege.toString(), FileClass.ImgFile.toString());
        input.getReleaseScopes().forEach((k) -> {
            k.setKeyId(NewsCollege.getId());
            k.setGmtCreate(new Date());
            k.setGmtModified(new Date());
            k.setCreatorCode("");
            k.setCreatorId("");
            k.setCreatorName("");
            k.setPublishType(input.getItem().getPublishType());
          //  k.setPublishingDepartmentId(input.getItem().getPublishingDepartmentId());
           // k.setPublishingDepartment(input.getItem().getPublishingDepartment());
        });
        releaseScopeMapper.insertEleaseScopes(input.getReleaseScopes());
        //output.setReleaseScopes(releaseScopeMapper.selectByPublishTypeKeyId(NewsCollege.getId().toString(),NewsCollege.getPublishType()));
        NewsCollege.setFiles(fileService.getFiles(NewsCollege.getId().toString(),FileBusinessType.NewsCollege.toString(),FileClass.File.toString()));
        NewsCollege.setImgFiles(fileService.getFiles(NewsCollege.getId().toString(),FileBusinessType.NewsCollege.toString(),FileClass.ImgFile.toString()));
        output.setItem(NewsCollege);
        return output;
    }
/**
 *  创建人:王增立
 *  备注: 删除新闻
 *  时间: 2019/4/26 15:13
 *  参数: 
 */
    public DeleteNewsCollegeOutput deleteNewsCollege(DeleteNewsCollegeInput input) {
        DeleteNewsCollegeOutput output = new DeleteNewsCollegeOutput();
        NewsCollege oldEntity = newsCollegeMapper.selectByPrimaryKey(input.getItem().getId());
        oldEntity.setDeleted(true);
        newsCollegeMapper.updateByPrimaryKey(oldEntity);
        output.setItem(oldEntity);
        return output;
    }
/**
 *  创建人:王增立
 *  备注: 编辑新闻
 *  时间: 2019/4/26 15:14
 *  参数: 
 */
    @Transactional
    public EditNewsCollegeOutput editNewsCollege(EditNewsCollegeInput input) throws Exception {
        EditNewsCollegeOutput output = new EditNewsCollegeOutput();
        NewsCollege oldEntity = newsCollegeMapper.selectByPrimaryKey(input.getItem().getId());

        oldEntity.setTitle(input.getItem().getTitle());
        oldEntity.setContent(input.getItem().getContent());
        oldEntity.setPublishType(input.getItem().getPublishType());
        oldEntity.setPublisherName(input.getItem().getPublisherName());
        oldEntity.setPublishingDepartmentId(input.getItem().getPublishingDepartmentId());
        oldEntity.setPublishingDepartment(input.getItem().getPublishingDepartment());
        oldEntity.setReleaseTime(input.getItem().getReleaseTime());
        oldEntity.setGmtModified(new Date());
        oldEntity.setCategory(input.getItem().getCategory());
        oldEntity.setImgUrl(input.getItem().getImgUrl());
        oldEntity.setThumbnailUrl(input.getItem().getThumbnailUrl());
        releaseScopeMapper.deleteByKeyId(oldEntity.getId().toString(),oldEntity.getPublishType());

        input.getReleaseScopes().forEach((k) -> {
            k.setKeyId(oldEntity.getId());
            k.setGmtCreate(new Date());
            k.setGmtModified(new Date());
            k.setCreatorCode("");
            k.setCreatorId("");
            k.setCreatorName("");
            k.setPublishType(input.getItem().getPublishType());
           // k.setPublishingDepartmentId(input.getItem().getPublishingDepartmentId());
           // k.setPublishingDepartment(input.getItem().getPublishingDepartment());
        });
        releaseScopeMapper.insertEleaseScopes(input.getReleaseScopes());
        newsCollegeMapper.updateByPrimaryKey(oldEntity);

        fileService.saveFiles(input.getItem().getImgFiles(), input.getItem().getId().toString(), FileBusinessType.NewsCollege.toString(), FileClass.ImgFile.toString());
        fileService.saveFiles(input.getItem().getFiles(), input.getItem().getId().toString(), FileBusinessType.NewsCollege.toString(),FileClass.File.toString());
        //oldEntity.setReleaseScopes(releaseScopeMapper.selectByPublishTypeKeyId(oldEntity.getId().toString(),oldEntity.getPublishType()));
        oldEntity.setFiles(fileService.getFiles(oldEntity.getId().toString(),FileBusinessType.NewsCollege.toString(),FileClass.File.toString()));
        oldEntity.setImgFiles(fileService.getFiles(oldEntity.getId().toString(),FileBusinessType.NewsCollege.toString(),FileClass.ImgFile.toString()));
        output.setItem(oldEntity);
        return output;
    }
/**
 *  创建人:王增立
 *  备注: 获取新闻
 *  时间: 2019/4/26 15:14
 *  参数: 
 */
    public GetNewsCollegeOutput getNewsCollege(GetNewsCollegeInput input) throws Exception {


        GetNewsCollegeOutput output = new GetNewsCollegeOutput();

        Example example = new Example(NewsCollege.class);

        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("deleted", 0);
        if (!isBlank(input.getStatus())) {
            criteria.andEqualTo("status", input.getStatus());//普通用户只查询已发布的
        }
        if (!isBlank(input.getPublishType())) {
            criteria.andEqualTo("publishType", input.getPublishType());
        }
        if (!isBlank(input.getPublishingDepartmentId())) {
            criteria.andEqualTo("publishingDepartmentId", input.getPublishingDepartmentId());
        }

        if (!isBlank(input.getColumnPlateCode()))
        {
            criteria.andEqualTo("columnPlateCode", input.getColumnPlateCode());
        }
        //增加权限发布范围
        PrivilegeTool PrivilegeToolList= privilegeService.GetPrivilegeByOrgPath("1");
        if(!PrivilegeToolList.isErre()&&!PrivilegeToolList.isAdmin()&&PrivilegeToolList.getPrivilegeLiat().size()>0){
            criteria.andIn("id",PrivilegeToolList.getPrivilegeLiat());
        }else if(PrivilegeToolList.isErre()){
            //错误条件不会查到信息
            criteria.orEqualTo("status",500);
        }
        if (!PrivilegeToolList.isAdmin()) {
            criteria.andEqualTo("status", 1);//普通用户只查询已发布的
        }

        if(!isBlank(input.getTitle())) {
            Example.Criteria criteria2 = example.createCriteria();
            criteria2.orLike("title", "%" + input.getTitle() + "%");

            criteria2.orLike("content", "%" + input.getTitle() + "%");
            example.and(criteria2);
        }

        PageHelper.startPage(input.getPage().getPageNo(), input.getPage().getPageSize(), "Id desc");
        List<NewsCollege> ls = newsCollegeMapper.selectByExample(example);
        PageInfo<NewsCollege> page = new PageInfo<>(ls);
        //浏览次数
        List<NewsCollege> lsResult=page.getList();
        lsResult.forEach(it->{

            GetBrowseCountInput countInput=new GetBrowseCountInput();
            countInput.setId(it.getId());
            countInput.setKeyType(it.getPublishType());
            Long count=browseRecordService.getBroweCount(countInput).getBrowseCount();
            it.setBroweCount(count);

        });
        output.setItems(new PagedResult<NewsCollege>(lsResult, (int) page.getTotal()));
        return output;

    }
/**
 *  创建人:王增立
 *  备注: 加载新闻
 *  时间: 2019/4/26 15:14
 *  参数: 
 */
    public PageLoadOutput pageLoad(PageLoadInput input) throws Exception {
        PageLoadOutput output = new PageLoadOutput();


        Example example = new Example(NewsCollege.class);
        Example.Criteria criteria = example.createCriteria();

        criteria.andEqualTo("deleted", 0);
        //criteria.andLike("title", "%"+input.getTitle()+"%");

        if (!isBlank(input.getStatus())) {
            criteria.andEqualTo("status", input.getStatus());//普通用户只查询已发布的
        }
        if (!isBlank(input.getPublishType())) {
            criteria.andEqualTo("publishType", input.getPublishType());
        }
        //增加权限发布范围
        PrivilegeTool PrivilegeToolList= privilegeService.GetPrivilegeByOrgPath("1");//1新闻2公告3发文4学院天地
        if(!PrivilegeToolList.isErre()&&!PrivilegeToolList.isAdmin()&&PrivilegeToolList.getPrivilegeLiat().size()>0){
            criteria.andIn("id",PrivilegeToolList.getPrivilegeLiat());
        }else if(PrivilegeToolList.isErre()){
            //错误条件不会查到信息
            criteria.orEqualTo("status",500);
        }
        if (!PrivilegeToolList.isAdmin()) {
            criteria.andEqualTo("status", 1);//普通用户只查询已发布的
        }
        PageHelper.startPage(input.getPage().getPageNo(), input.getPage().getPageSize(), "Id desc");
        List<NewsCollege> ls = newsCollegeMapper.selectByExample(example);

        Example exampleTwo = new Example(ColumnPlate.class);
        Example.Criteria criteriaTwo = exampleTwo.createCriteria();
        criteriaTwo.andEqualTo("keyType", 1);//1新闻2公告3发文4学院天地
        criteriaTwo.andEqualTo("deleted",0);
        List<ColumnPlate> lsTwo = columnPlateMapper.selectByExample(exampleTwo);
        output.setColumnPlates(lsTwo);

        PageInfo<NewsCollege> page = new PageInfo<>(ls);

        //浏览次数
        List<NewsCollege> lsResult=page.getList();
        lsResult.forEach(it->{

            GetBrowseCountInput countInput=new GetBrowseCountInput();
            countInput.setId(it.getId());
            countInput.setKeyType(it.getPublishType());
            Long count=browseRecordService.getBroweCount(countInput).getBrowseCount();
            it.setBroweCount(count);

        });
        output.setItems(new PagedResult<NewsCollege>(lsResult, (int) page.getTotal()));
        return output;
    }
/**
 *  创建人:王增立
 *  备注: 根据新闻Id获取新闻信息
 *  时间: 2019/4/26 15:15
 *  参数: 
 */
    public GetNewsCollegeOutput getNewsCollegeById(GetNewsCollegeInput input) throws Exception {
        GetNewsCollegeOutput output = new GetNewsCollegeOutput();
        //logger.error("log4j2 error!");
        Example example = new Example(NewsCollege.class);
        Example.Criteria criteria = example.createCriteria();
        //criteria.andEqualTo("keyType",input.getPublishType());//2:公告 3：发文
        //List<ColumnPlate> ls=columnPlateMapper.selectByExample(example);


        NewsCollege object = newsCollegeMapper.selectByPrimaryKey(input.getId());
        //object.setReleaseScopes(releaseScopeMapper.selectByPublishTypeKeyId(object.getId().toString(),object.getPublishType()));
        object.setFiles(fileService.getFiles(object.getId().toString(),FileBusinessType.NewsCollege.toString(),FileClass.File.toString()));
        object.setImgFiles(fileService.getFiles(object.getId().toString(),FileBusinessType.NewsCollege.toString(),FileClass.ImgFile.toString()));
        //ObjectUnit.Copy(object,output);
        if(input.getType()!=null&&input.getType().equals("view")){
            CreateBrowseRecordInput cbrInput=new CreateBrowseRecordInput(){
            };
            BrowseRecord br=new BrowseRecord();
            br.setArticleId(input.getId());
            br.setUsercode("");
            br.setUserid("");
            br.setUsername("");
            br.setKeyType(object.getPublishType());
            //br.setKeyType(input.g);
            cbrInput.setItem(br);
            browseRecordService.createBrowseRecord(cbrInput);
        }
        GetBrowseCountInput countInput=new GetBrowseCountInput();
        countInput.setId(object.getId());
        countInput.setKeyType(object.getPublishType());
        Long count=browseRecordService.getBroweCount(countInput).getBrowseCount();
        object.setBroweCount(count);
        output.setItem(object);

        //scopes
        Example exam=new Example(ReleaseScope.class);
        Example.Criteria cri = exam.createCriteria();
        cri.andEqualTo("keyId",object.getId());
        cri.andEqualTo("deleted","0");
        // Long[] types=new Long[]{2L,3L};
        List<Long> types=new ArrayList<Long>();
        types.add(1L);
        types.add(4L);
        cri.andIn("publishType",types);
        List<ReleaseScope> releaseScopes=releaseScopeMapper.selectByExample(exam);
        output.setReleaseScopes(releaseScopes);

        return output;

    }
/**
 *  创建人:王增立
 *  备注: 首页获取所有新闻
 *  时间: 2019/4/26 15:16
 *  参数: 
 */
    public GetNewsCollegeOutput getHomePageNewsCollege(GetHomePageNewsCollegeInput input) throws Exception {
        GetNewsCollegeOutput output = new GetNewsCollegeOutput();

        //增加权限发布范围
        PrivilegeTool PrivilegeToolList= privilegeService.GetPrivilegeByOrgPath(input.getPublishType());

        input.setOrgPathIDs(PrivilegeToolList.getOrgIdPath());

        List<NewsCollege> ls = new ArrayList();
        if(PrivilegeToolList.isAdmin()){
            ls= newsCollegeMapper.selectAdminBylimit(input);
        }else{
            ls= newsCollegeMapper.selectBylimit(input);
        }


        PageInfo<NewsCollege> page = new PageInfo<>(ls);
        List<NewsCollege> resultLs= page.getList();
        for(NewsCollege item:resultLs){
            item.setFiles(fileService.getFiles(item.getId().toString(), FileBusinessType.NewsCollege.toString(),FileClass.File.toString()));
        }
        //浏览次数
        List<NewsCollege> lsResult=page.getList();
        lsResult.forEach(it->{

            GetBrowseCountInput countInput=new GetBrowseCountInput();
            countInput.setId(it.getId());
            countInput.setKeyType(it.getPublishType());
            Long count=browseRecordService.getBroweCount(countInput).getBrowseCount();
            it.setBroweCount(count);

        });
        output.setItems(new PagedResult<NewsCollege>(lsResult, (int) page.getTotal()));
        return output;

    }
/**
 *  创建人:王增立
 *  备注: 首页获取图片新闻
 *  时间: 2019/4/26 15:18
 *  参数: 
 */
    public GetNewsCollegeOutput getHomePageNewsPic(GetHomePageNewsCollegeInput input) throws Exception {
        GetNewsCollegeOutput output = new GetNewsCollegeOutput();
        //增加权限发布范围
        PrivilegeTool PrivilegeToolList= privilegeService.GetPrivilegeByOrgPath(input.getPublishType());

        input.setOrgPathIDs(PrivilegeToolList.getOrgIdPath());
        List<NewsCollege> ls = new ArrayList();
        if(PrivilegeToolList.isAdmin()){
            ls= newsCollegeMapper.selectAdminPicBylimit(input);
        }else{
            ls= newsCollegeMapper.selectPicBylimit(input);
        }
        PageInfo<NewsCollege> page = new PageInfo<>(ls);

        //浏览次数
        List<NewsCollege> lsResult=page.getList();
        lsResult.forEach(it->{

            GetBrowseCountInput countInput=new GetBrowseCountInput();
            countInput.setId(it.getId());
            countInput.setKeyType(it.getPublishType());
            Long count=browseRecordService.getBroweCount(countInput).getBrowseCount();
            it.setBroweCount(count);

        });

        output.setItems(new PagedResult<NewsCollege>(lsResult, (int) page.getTotal()));


        return output;

    }
}
